package com.sls.game.service.impl;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.DataConversion;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.DownstreamUserDAO;
import com.sls.game.dao.GoodsInfoManageDAO;
import com.sls.game.pojo.DownstreamUserInfo;
import com.sls.game.pojo.GoodsManageInfo;
import com.sls.game.pojo.user.LocalGoodsNotice;
import com.sls.game.service.LocalGoodsModifyService;

/**
 * 
 * @Description：商品基础数据修改（上下架），主动通知下游用户
 * @author wxg
 * @Date：2013-6-19
 * 
 */
@Service("localGoodsModifyService")
public class LocalGoodsModifyServiceImpl implements LocalGoodsModifyService {
	private static Logger log = Logger
			.getLogger(LocalGoodsModifyServiceImpl.class);

	private Gson gson = null;

	public LocalGoodsModifyServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Resource(name = "goodsInfoManageDAO")
	private GoodsInfoManageDAO goodsInfoManageDAO;
	@Resource(name = "downstreamUserDAO")
	private DownstreamUserDAO downstreamUserDAO;

	/**
	 * 商品信息修改，主动通知下游用户
	 * 
	 * @param body
	 * @param head
	 */
	@Override
	public void noticeUserAboutGoods(String body, Head head) {
		if (log.isInfoEnabled()) {
			log.info("进入Service开始处理[" + head.getRequestId() + "]的请求");
		}
		LocalGoodsNotice lgn = gson.fromJson(body, LocalGoodsNotice.class);
		boolean flag = checkDataOfNotice(lgn);
		if (flag) {
			String templateCode = lgn.getTemplateCode();
			List<DownstreamUserInfo> list = null;
			DownstreamUserInfo userInfo = new DownstreamUserInfo();
			userInfo.setTemplateCode(templateCode);
			list = downstreamUserDAO.queryInfoByTemplateCode(userInfo);
			if (list != null && list.size() > 0) {
				for (DownstreamUserInfo user : list) {
					String userNo = user.getUserNo();
					String secretKey = user.getSecretKey();
					String goodsSourceModUrl = user.getGoodsSourceModUrl();
					HashMap<String, String> map = getMsgPara(lgn, userNo,
							secretKey);
					sendMsg(goodsSourceModUrl, map, head);
				}
			}
		}
	}

	/**
	 * 向下游发送消息
	 * 
	 * @param goodsSourceModUrl
	 * @param map
	 * @param head
	 */
	private void sendMsg(String goodsSourceModUrl, HashMap<String, String> map,
			Head head) {
		HttpClient hc = new HttpClient();
		try {
			log.info("请求ID：" + head.getRequestId() + "，商品变更主动通知下游："
					+ "\n goodsSourceModUrl=" + goodsSourceModUrl
					+ "\n userNo=" + map.get("userNo") + "\n goodsId="
					+ map.get("goodsId") + "\n goodsName="
					+ map.get("goodsName") + "\n brandId=" + map.get("brandId")
					+ "\n price=" + map.get("price") + "\n parValue="
					+ map.get("parValue") + "\n rechargeMode="
					+ map.get("rechargeMode") + "\n description="
					+ map.get("description") + "\n sign=" + map.get("sign"));
			if (StringUtils.isNotEmpty(goodsSourceModUrl)) {
				String xmlStr = hc.doPost(goodsSourceModUrl, map);
				log.info("请求ID：" + head.getRequestId() + "，下游用户的返回结果：" + xmlStr);
			}

		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "，主动通知下游用户出现异常！", e);
		}
	}

	/**
	 * 
	 * @param goodsId
	 * @param secretKey
	 * @return
	 */
	private HashMap<String, String> getMsgPara(LocalGoodsNotice lgn,
			String userNo, String secretKey) {
		String goodsId = lgn.getGoodsId();
		HashMap<String, String> map = new HashMap<String, String>();
		GoodsManageInfo gm = goodsInfoManageDAO
				.queryGoodsInfoByGoodsId(goodsId);
		if (gm != null) {
			String goodsName = gm.getGoodsName();
			String brandId = gm.getGoodsCategoryId();
			int saleprice = gm.getCommonSalePrice(); // 单位：厘
			String price = DataConversion.converIntegerToString(saleprice + "");
			int goodsMoney = gm.getGoodsMoney(); // 单位：厘
			String parValue = DataConversion.converIntegerToString(goodsMoney
					+ "");
			String goodsState = gm.getGoodsState();
			String rechargeMode = gm.getRechargeMode();
			String description = gm.getGoodsDescription();
			// MD5签名串
			String sign = getSign(goodsId, goodsName, brandId, price, parValue,
					rechargeMode, description, secretKey);
			map.put("userNo", userNo);
			map.put("goodsId", goodsId);
			map.put("goodsName", goodsName);
			map.put("brandId", brandId);
			map.put("price", price);
			map.put("parValue", parValue);
			map.put("goodsState", goodsState);
			map.put("rechargeMode", rechargeMode);
			map.put("description", description);
			map.put("sign", sign);
		}
		return map;
	}

	/**
	 * 生成MD5签名串
	 * 
	 * @param goodsId
	 * @param goodsName
	 * @param brandId
	 * @param price
	 * @param parValue
	 * @param rechargeMode
	 * @param description
	 * @param secretKey
	 * @return
	 */
	private String getSign(String goodsId, String goodsName, String brandId,
			String price, String parValue, String rechargeMode,
			String description, String secretKey) {
		StringBuilder sb = new StringBuilder();
		sb.append(goodsId);
		sb.append(goodsName);
		sb.append(brandId);
		sb.append(price);
		sb.append(parValue);
		sb.append(rechargeMode);
		sb.append(description);
		sb.append(secretKey);

		String data = sb.toString().trim();
		String sign = UtilMD5Encryption.createMD5EncryptionOfUTF8(data);
		return sign;
	}

	/**
	 * 
	 * @param lgn
	 * @return
	 */
	private boolean checkDataOfNotice(LocalGoodsNotice lgn) {
		boolean flag = false;
		String goodsId = lgn.getGoodsId();
		if (StringUtils.isEmpty(goodsId)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PRODCODE_EMPTY.getCode(),
					ExceptionCodeDes.PRODCODE_EMPTY.getDescription());
		} else {
			flag = true;
		}
		return flag;
	}

}
